package com.happymmall.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.happymmall.service.UserService;
import com.happymmall.service.impl.UserServiceImpl;
import com.happymmall.util.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/update_information.do")
public class UpdateInformationServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从请求头获得Token
        String token = req.getHeader("Authorization");
        // 提取用户ID
        Integer userId = JwtUtils.extractClaim(token, claims -> claims.get("userId", Integer.class));//Lambda
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String question = req.getParameter("question");
        String answer = req.getParameter("answer");

        UserService userservice = new UserServiceImpl();
        boolean result = userservice.update_information(email, phone, question, answer, userId);
        if (result) {
            resp.setContentType("application/json;charset=utf-8");
            Map<String, Object> resultData = new HashMap();
            resultData.put("status", 0);
            resultData.put("msg", "更新个人信息成功");

            JSONObject jsonObject = new JSONObject();
            String info = jsonObject.toJSONString(resultData);
            PrintWriter out = resp.getWriter();
            out.write(info);
        } else {
            resp.setContentType("application/json;charset=utf-8");
            Map<String, Object> resultData = new HashMap();
            resultData.put("status", 1);
            resultData.put("msg", "用户未登录");

            JSONObject jsonObject = new JSONObject();
            String info = jsonObject.toJSONString(resultData);
            PrintWriter out = resp.getWriter();
            out.write(info);
        }


    }
}
